-- variables
BGDefender_VERSION = "1.4.1";

local DefaultBGDefenderVars = {
	["BGDefenderVersion"]         = "1.4.1",  -- Version
	["BGDefenderLanguage"]        = "zhCN",     -- Output Language
	["BGDefenderAutoHide"]        = 1,      -- Auto hide on zone change
	-- 1.4
    -- ["BGDefenderUseLastBase"]     = 1,      -- save last base (subzone)
	-- ["BGDefenderLastBaseTimeout"] = 20,     -- autoclear last base in seconds
    
    ["BGDefenderCalls"]           =  { };
};

local DefaultBGDefenderCalls = {
    ["TW"] = {
        ["help"] = "$base 斷旗!!斷旗!! 敵多!! 快快支援!!",
        ["safe"] = "$base 已經安全唷! 感謝幫忙^^",
        ["inc"]  = "注意! $base 有 $num 人來襲!! 麻煩支援!!",
        ["inc+"] = "哇!! $base 超過五人開火車來囉! 麻煩盡速支援!!";
    },
    ["CN"] = {
        ["help"] = "$base 速度支援！敌人大量！",
        ["safe"] = "$base 已经安全了！感谢支援~~",
        ["inc"]  = "警报！$base 有 $num 人进攻！请求支援！！.",
        ["inc+"] = "$base 超过5人进攻了！！！速度支援！！";
    },
    ["EN"] = {
        ["help"] = "$base help needed.",
        ["safe"] = "$base safe.",
        ["inc"]  = "$base $num incoming.",
        ["inc+"] = "$base more than 5 incoming.";
    };
};

BGDefender_Vars_Loaded = nil;
TimeSinceLastUpdate    = 0;

function out(text)
	DEFAULT_CHAT_FRAME:AddMessage(text)
 	UIErrorsFrame:AddMessage(text, 1.0, 1.0, 0, 1, 10) 
end


function BGDefender_close()
    BG_BASE_DEFENDER_OPTIONS["BGDefenderAutoHide"] = BGDefender_Toggle(0)
end


-- sending the chat message
function BGDefender_NumCall(arg1)
	local location = nil; 
   	local call = "";

   
   	-- get output language
   	local l = BG_BASE_DEFENDER_OPTIONS["BGDefenderLanguage"];
   	if (l ==	"") then
    	l = getLanguage();
   	end
  
   	if (not BGDefender_isInBG()) then
    	if (l == "enUS" or l == "enGB") then
        	out("You are not in a battleground!");
      	elseif (l == "zhTW") then
        	out("你現在不是在戰場中!");
      	elseif (l == "zhCN") then
        	out("你现在不在战场中！");
		else
		  	out("You are not in a battleground!");
		end
      	return;  
   	end

            
    
      location = GetSubZoneText();
	
      if (location ~= "") then
        
        
  
        if(arg1==6) then
            call = BG_BASE_DEFENDER_OPTIONS["BGDefenderCalls"]["inc+"];
        elseif(arg1==0) then
            call = BG_BASE_DEFENDER_OPTIONS["BGDefenderCalls"]["safe"];
        elseif(arg1==9) then
            call = BG_BASE_DEFENDER_OPTIONS["BGDefenderCalls"]["help"];
        else 
            call = BG_BASE_DEFENDER_OPTIONS["BGDefenderCalls"]["inc"];
            call = string.gsub(call, "$num", arg1);
        end

        call = string.gsub(call, "$base", location);
        
		SendChatMessage(call, "BATTLEGROUND");
		-- out(call);
	else
	    if (l == "enUS" or l == "enGB") then
	        out("You are not near a point to defend!");
		elseif ( l == "zhTW" ) then
			out("你並未靠近任何一個防禦點喔!");
		elseif ( l == "zhCN" ) then
			out("你并未靠近任何一个防御点！");
		else
          	out("You are not near a point to defend!");
		end
	end
end

function BGDefender_OnClick(arg1)
   id = this:GetID()
   out("BGDefender: OnClick: " .. this:GetName() .. " ,ID: " .. id .. " ,Button:" ..arg1)
end

function BGDefender_InitSlider(slider)
    local sl = getglobal(slider)
	sl.tooltipText = "This is the Tooltip hint"; 
	getglobal(slider .. "Low"):SetText("1");
	getglobal(slider .. "High"):SetText("100"); 
	getglobal(slider .. "Text"):SetText("5");
end


function BGDefender_SlashCommandHandler(msg)
	msg = strlower(msg);
    
    local wList = GetWords(msg);

	if (wList[1] == "reset") then
	
        ReloadUI();
        -- reset saved variables
        BGDefender_loadDefault();
	 
	elseif (wList[1] == "help") then
	
        DEFAULT_CHAT_FRAME:AddMessage("BG Defender v1.41 中文版"..BGDefender_VERSION, 1.0, 0.5, 0.0);
 	    DEFAULT_CHAT_FRAME:AddMessage("/bgd [show/hide]     - 显示/隐藏 使用界面", 1.0, 0.5, 0.0);
        DEFAULT_CHAT_FRAME:AddMessage("/bgd reset              - 重新加载 UI", 1.0, 0.5, 0.0);
 	    
        -- 1.2
        DEFAULT_CHAT_FRAME:AddMessage("/bgd lang [en/cn/tw]    - 设定输出语言", 1.0, 0.5, 0.0);
	    DEFAULT_CHAT_FRAME:AddMessage("/bgd status             - 显示目前各项设定值", 1.0, 0.5, 0.0);
	 
        -- 1.3
        DEFAULT_CHAT_FRAME:AddMessage("/bgd call (help/safe/inc/inc+) [string] - 设定自定义喊话", 1.0, 0.5, 0.0);
        DEFAULT_CHAT_FRAME:AddMessage("        字串变量: $base - 目前防御点, $num - 按键 1-5", 1.0, 0.5, 0.0);
        DEFAULT_CHAT_FRAME:AddMessage("        范例: /bgd call inc $base $num 个敌人进攻！支援！", 1.0, 0.5, 0.0);
		DEFAULT_CHAT_FRAME:AddMessage(" ======2区 玛法里奥 亡者之殇 汉化======", 1.0, 0.5, 0.0);
       
     
	elseif (wList[1] == "show") then
	
		BG_BASE_DEFENDER_OPTIONS["BGDefenderAutoHide"] = BGDefender_Toggle(1)
		
	elseif (wList[1] == "hide") then
	
	    BG_BASE_DEFENDER_OPTIONS["BGDefenderAutoHide"] = BGDefender_Toggle(0)
	    
    elseif (wList[1] == "status") then
    
        BGDefender_ShowVars();
        
    elseif (wList[1] == "call") then   

        
        call = "";
        if (getn(wList) >= 3) then
        
            -- rebuild string
            call = wList[3];
            for i=4,getn(wList) do
                call = call.." "..wList[i]
            end
            
            if (wList[2] == "help") then
                BG_BASE_DEFENDER_OPTIONS["BGDefenderCalls"]["help"] = call;
                DEFAULT_CHAT_FRAME:AddMessage("call \"help\" set to \""..BG_BASE_DEFENDER_OPTIONS["BGDefenderCalls"]["help"].."\"", 1.0, 0.5, 0.0);
            elseif (wList[2] == "safe") then
                BG_BASE_DEFENDER_OPTIONS["BGDefenderCalls"]["safe"] = call;
                DEFAULT_CHAT_FRAME:AddMessage("call \"safe\" set to \""..BG_BASE_DEFENDER_OPTIONS["BGDefenderCalls"]["safe"].."\"", 1.0, 0.5, 0.0);
            elseif (wList[2] == "inc") then
                BG_BASE_DEFENDER_OPTIONS["BGDefenderCalls"]["inc"]  = call;
                DEFAULT_CHAT_FRAME:AddMessage("call \"inc\" set to \""..BG_BASE_DEFENDER_OPTIONS["BGDefenderCalls"]["inc"].."\"", 1.0, 0.5, 0.0);
            elseif (wList[2] == "inc+") then
                BG_BASE_DEFENDER_OPTIONS["BGDefenderCalls"]["inc+"] = call;
                DEFAULT_CHAT_FRAME:AddMessage("call \"inc+\" set to \""..BG_BASE_DEFENDER_OPTIONS["BGDefenderCalls"]["inc+"].."\"", 1.0, 0.5, 0.0);
            else
                DEFAULT_CHAT_FRAME:AddMessage("unknown call ".. wList[2], 1.0, 0.5, 0.0);    
            end 
        else
            DEFAULT_CHAT_FRAME:AddMessage("missing call parameter and string /bgd call (help/safe/inc/inc+) [string]", 1.0, 0.5, 0.0);    
        end
       
        
     
    elseif (wList[1] == "lang"  or wList[1] == "language") then
    
    	if (wList[2] == "en" or wList[2] == "engb" or wList[2] == "enus" or wList[2] == "us") then
          
		  	BG_BASE_DEFENDER_OPTIONS["BGDefenderLanguage"] = "enUS";
          	DEFAULT_CHAT_FRAME:AddMessage("BG Defender language set to EN", 1.0, 0.5, 0.0);
            BG_BASE_DEFENDER_OPTIONS["BGDefenderCalls"] = CloneTable(DefaultBGDefenderCalls["EN"]);	
          
     	elseif (wList[2] == "tw" or wList[2] == "zhtw" or wList[2] == "tw") then
          
		  	BG_BASE_DEFENDER_OPTIONS["BGDefenderLanguage"] = "zhTW";
          	DEFAULT_CHAT_FRAME:AddMessage("BG Defender 語言輸出設定為 TW", 1.0, 0.5, 0.0);
            BG_BASE_DEFENDER_OPTIONS["BGDefenderCalls"] = CloneTable(DefaultBGDefenderCalls["TW"]);	

      	elseif (wList[2] == "cn" or wList[2] == "zhcn" or wList[2] == "cn") then
          
		  	BG_BASE_DEFENDER_OPTIONS["BGDefenderLanguage"] = "zhCN";
          	DEFAULT_CHAT_FRAME:AddMessage("BG Defender 语言输出设定为 CN", 1.0, 0.5, 0.0);
            BG_BASE_DEFENDER_OPTIONS["BGDefenderCalls"] = CloneTable(DefaultBGDefenderCalls["DE"]);	
      
	  	else
      
      		BG_BASE_DEFENDER_OPTIONS["BGDefenderLanguage"] = "";
      		DEFAULT_CHAT_FRAME:AddMessage("BG Defender language set to client dependant ("..getLanguage()..")", 1.0, 0.5, 0.0);
      
	  	end
      
	else
	
	 	BG_BASE_DEFENDER_OPTIONS["BGDefenderAutoHide"] = BGDefender_Toggle();
	 
	end
end

function BGDefender_ShowVars()
 
   DEFAULT_CHAT_FRAME:AddMessage("BG Defender Variables", 1.0, 0.5, 0.0);
   DEFAULT_CHAT_FRAME:AddMessage("Version     - "..BG_BASE_DEFENDER_OPTIONS["BGDefenderVersion"], 1.0, 0.5, 0.0);
   DEFAULT_CHAT_FRAME:AddMessage("AutoHide   - "..BG_BASE_DEFENDER_OPTIONS["BGDefenderAutoHide"], 1.0, 0.5, 0.0);
   
   if (BG_BASE_DEFENDER_OPTIONS["BGDefenderLanguage"] == "") then
      	DEFAULT_CHAT_FRAME:AddMessage("Language - client dependant ("..getLanguage()..")", 1.0, 0.5, 0.0);
   else
      	DEFAULT_CHAT_FRAME:AddMessage("Language - "..BG_BASE_DEFENDER_OPTIONS["BGDefenderLanguage"], 1.0, 0.5, 0.0);
   end
   
    DEFAULT_CHAT_FRAME:AddMessage("Calls         - help \""..BG_BASE_DEFENDER_OPTIONS["BGDefenderCalls"]["help"].."\"", 1.0, 0.5, 0.0);
    DEFAULT_CHAT_FRAME:AddMessage("                   safe \""..BG_BASE_DEFENDER_OPTIONS["BGDefenderCalls"]["safe"].."\"", 1.0, 0.5, 0.0);
    DEFAULT_CHAT_FRAME:AddMessage("                   inc   \""..BG_BASE_DEFENDER_OPTIONS["BGDefenderCalls"]["inc"].."\"", 1.0, 0.5, 0.0);
    DEFAULT_CHAT_FRAME:AddMessage("                   inc+ \""..BG_BASE_DEFENDER_OPTIONS["BGDefenderCalls"]["inc+"].."\"", 1.0, 0.5, 0.0);
    DEFAULT_CHAT_FRAME:AddMessage("                   zone \""..GetZoneText().."\"", 1.0, 0.5, 0.0);
    DEFAULT_CHAT_FRAME:AddMessage("                   sub-zone \""..GetSubZoneText().."\"", 1.0, 0.5, 0.0);
    DEFAULT_CHAT_FRAME:AddMessage("                   minimap-zone \""..GetMinimapZoneText().."\"", 1.0, 0.5, 0.0);

        
end

function getLanguage()
  	local loc = GetLocale();
  	
  	if (loc == "enUS" or loc == "zhTW" or loc == "enGB" or loc == "zhCN") then
     	return loc;
  	end
  	return "enUS";
end
    


-- shoh/hide window per chat command
function BGDefender_Toggle(num)
	local frame  = getglobal("RIC5");
	local status = nil; 
   	if (frame) then
    	if (num == 0) then
			frame:Hide();
			status = 1;
		elseif (num == 1) then
		 	frame:Show();
		 	status = 0;
		else	
    		if(frame:IsVisible()) then
      			frame:Hide();
      			status = 1;
    		else
      			frame:Show();
      			status = 0;
    		end
    	end
    	return status;
   	end
end

function BGDefender_isInBG() 
  local zone = GetZoneText();
      
  if (zone == "Alterac Valley" or zone == "奥特兰克山谷") then
     return true;
  end

  if (zone == "Arathi Basin" or zone == "阿拉希盆地") then
     return true;
  end

  if (zone == "Warsong Gulch" or zone == "战歌峡谷") then
     return true;
  end

  if (zone == "Warsong Lumber Mill" or zone == "风暴之眼") then
     return true;
  end

  if (zone == "Silverwing Hold" or zone == "银翼要塞") then
     return true;
  end
  
  if (zone == "Eye of the Storm" or zone == "风暴之眼") then
     return true;
  else
     return false;
  end       
end

function BGDefender_OnLoad()
	-- register events

  	-- needed for saved variables
  	this:RegisterEvent("ADDON_LOADED");
  	this:RegisterEvent("VARIABLES_LOADED");

  	-- auto toggle frame on enter/exit bg
  	this:RegisterEvent("ZONE_CHANGED_NEW_AREA");

    
    -- init vars
    TimeSinceLastUpdate = 0;
    
  	out("BG Defender loaded (ver "..BGDefender_VERSION.."). 请输入/bgd显示设定说明.");

	SLASH_BGDefender1 = "/BGDefender";
  	SLASH_BGDefender2 = "/bgd";

  	SlashCmdList["BGDefender"] = function(msg)
		BGDefender_SlashCommandHandler(msg);
	end
end



function BGDefender_OnEvent()
    if (event == "ZONE_CHANGED_NEW_AREA") then
	   if(BGDefender_isInBG()) then                      
	       BGDefender_Toggle(1);
       elseif (BG_BASE_DEFENDER_OPTIONS["BGDefenderAutoHide"] == 1) then
           BGDefender_Toggle(0);
       end
	
	elseif ((event == "ADDON_LOADED") and (strlower(arg1) == "BGDefender")) then
		BGDefender_Vars_Loaded = 1;
		BGDefender_Init();
		
	elseif (event == "VARIABLES_LOADED") then
		if (not BGDefender_Vars_Loaded ) then
			BGDefender_Vars_Loaded = 1;
			BGDefender_Init();
		end

	end
	
end

function BGDefender_Init() 
	-- new user 
	if (BG_BASE_DEFENDER_OPTIONS == nil) then
		BGDefender_loadDefault();
	-- old version
	elseif (BG_BASE_DEFENDER_OPTIONS["BGDefenderVersion"] ~= BGDefender_VERSION) then
            BGDefender_loadDefault();
    -- found saved variables	
  	else
    		-- soll noch was gemacht werden, wenn vars gefunden?
  	end
end

function BGDefender_loadDefault() 
    local loc        = GetLocale();
    BG_BASE_DEFENDER_OPTIONS = CloneTable(DefaultBGDefenderVars); 
    
    if (loc == "enUS" or loc == "enGB") then
    	BG_BASE_DEFENDER_OPTIONS["BGDefenderCalls"] = CloneTable(DefaultBGDefenderCalls["EN"]);	
	elseif (loc == "zhCN") then
	    BG_BASE_DEFENDER_OPTIONS["BGDefenderCalls"] = CloneTable(DefaultBGDefenderCalls["CN"]);	
	else
	   	BG_BASE_DEFENDER_OPTIONS["BGDefenderCalls"] = CloneTable(DefaultBGDefenderCalls["EN"]);		
	end
    
end

--Code by Grayhoof (SCT)
function CloneTable(t)				-- return a copy of the table t
	local new = {};					-- create a new table
	local i, v = next(t, nil);		-- i is an index of t, v = t[i]
	while i do
		if type(v)=="table" then 
			v=CloneTable(v);
		end 
		new[i] = v;
		i, v = next(t, i);			-- get next index
	end
	return new;
end

-- Code by wowwiki
function GetWords(str)
   local ret = {};
   local pos=0;
   while(true) do
     local word;
     _,pos,word=string.find(str, "^ *([^%s]+) *", pos+1);
     if(not word) then
       return ret;
     end
     table.insert(ret, word);
   end
 end
